/*
 * Copyright (c) JiaChaoYang 2024-5-29 MongoPlus版权所有
 * 适度编码益脑，沉迷编码伤身，合理安排时间，享受快乐生活。
 * email: j15030047216@163.com
 * phone: 15030047216
 * weChat: JiaChaoYang_
 */

package com.anwen.mongoa.config;

import com.anwen.mongo.handlers.TypeHandler;
import org.bson.types.Binary;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class InputStreamHandler implements TypeHandler<InputStream> {

    @Override
    public Object setParameter(String fieldName, InputStream obj) {
        try(ByteArrayOutputStream bos = new ByteArrayOutputStream()){
            byte[] b = new byte[1024];
            int len;
            while ((len = obj.read(b)) != -1) {
                bos.write(b, 0, len);
            }
            return bos.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public InputStream getResult(Object obj) {
        System.out.println(obj.getClass());
        return new ByteArrayInputStream(((Binary)obj).getData());
    }
}
